function lazyLoad(errorImg, loadingImg) {
  let clientHeight = document.documentElement.clientHeight
  let imgs = document.querySelectorAll('img')
  
  Array.prototype.forEach.call(imgs, (item) => {
    if (!item.dataset.src) return
    let imgPosition = item.getBoundingClientRect()
    if (imgPosition.bottom >= 0 && imgPosition.top < clientHeight) {
      (function() {
        let temImg = new Image()
        temImg.src = item.dataset.src
        item.src = loadingImg
        temImg.onload = () => {
          item.src = temImg.src
        }
        temImg.onerror = () => {
          item.src = errorImg
        }
        item.removeAttribute('data-src')
      })()
    }
  })
}

export default (errorImg, loadingImg) => {
  lazyLoad(errorImg, loadingImg)

  window.onload = () => {
    lazyLoad(errorImg, loadingImg)
  }

  document.onscroll = () => {
    lazyLoad(errorImg, loadingImg)
  }

  document.onresize = () => {
    lazyLoad(errorImg, loadingImg)
  }

  document.addEventListener('touchend', function() {
    lazyLoad(errorImg, loadingImg)
  }, false)

  document.addEventListener('touchmove', function() {
    lazyLoad(errorImg, loadingImg)
  }, false)
}
